package com.zaofan.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zaofan.bean.Admin;
import com.zaofan.bean.AdminType;
import com.zaofan.bean.Shop;
import com.zaofan.cache.FrontCache;
import com.zaofan.dao.AdminDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.utils.WebUtils;

public class AdminService {
	private static final Logger logger = LoggerFactory.getLogger(AdminService.class);
	private AdminDao adminDao = new AdminDao();
	private ShopService shopService = new ShopService();

	public void update(Admin admin) {
		adminDao.update(admin);
	}

	public Admin findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return adminDao.findOne(params);
	}

	public Admin findByName(String name) {
		Map<String, Object> params = new HashMap<>();
		params.put("name", name);
		return adminDao.findOne(params);
	}

	public Admin login(Admin admin) throws ServiceException {
		if (WebUtils.isEmpty(admin.getName())) {
			throw new ServiceException("请输入账户!!!");
		}
		if (WebUtils.isEmpty(admin.getPassword())) {
			throw new ServiceException("请输入账户密码!!!");
		}
		Admin target = this.findByName(admin.getName());
		logger.info("入参：{}，查询出　admin 用户：{}", admin, target);
		if (target == null) {
			throw new ServiceException("请输入正确的账户!!!");
		}
		if (!target.getPassword().equals(WebUtils.MD5(admin.getPassword()))) {
			throw new ServiceException("请输入正确的账户密码!!!");
		}
		return target;
	}

	public void updatePass(Integer id, String oldPass, String newPass)
			throws ServiceException {
		Admin target = this.findById(id);
		if (target == null) {
			throw new ServiceException("请输入正确的账户!!!");
		}
		if (WebUtils.isEmpty(oldPass)) {
			throw new ServiceException("请输入旧密码!!!");
		}
		if (WebUtils.isEmpty(newPass)) {
			throw new ServiceException("请输入新密码!!!");
		}
		if (!target.getPassword().equals(WebUtils.MD5(oldPass))) {
			throw new ServiceException("请输入正确的旧密码!!!");
		}
		target.setPassword(WebUtils.MD5(newPass));
		update(target);
	}

	public void addShopAdmin(Admin admin) throws ServiceException {
		if (WebUtils.isEmpty(admin.getName())) {
			throw new ServiceException("请输入登陆账号!!!");
		}
		if (WebUtils.isEmpty(admin.getPassword())) {
			throw new ServiceException("请输入登陆密码!!!");
		}
		Shop shop = shopService.findById(admin.getShopId());
		if (shop == null) {
			throw new ServiceException("请输入正确的商店信息!!!");
		}
		admin.setPassword(WebUtils.MD5(admin.getPassword()));
		admin.setType(AdminType.shopAdmin.ordinal());
		admin.setShopName(shop.getShopName());
		this.adminDao.add(admin);
	}

}